package cipher

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"errors"
)

/**
私钥封装接口
只用用来解密和签名
 */
type RsaPrivateCipher struct {
	priKey *rsa.PrivateKey
}
func (r *RsaPrivateCipher)SetPrivateKey(privateKey []byte) (err error){

	block, _ := pem.Decode(privateKey)
	if block == nil {
		err=errors.New("private key error!")
		return
	}
	r.priKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return
	}

	return
}
func (r *RsaPrivateCipher)Decrypt(src []byte) (dst []byte, err error){

	if r.priKey==nil{
		err=errors.New("RSA 用私钥解密时请先设置私钥！")
		return
	}

	return rsa.DecryptPKCS1v15(rand.Reader, r.priKey, src)
}
func (r *RsaPrivateCipher)Sign(src []byte)(dst []byte, err error){
	if r.priKey==nil{
		err=errors.New("RSA 用私钥签名时请先设置私钥！")
		return
	}
	h:=sha256.Sum256(src)
	return rsa.SignPKCS1v15(rand.Reader, r.priKey, crypto.SHA256,h[:])
}


